package com.ruoyi.web.core.facade;

import com.hnyc.IRegisterShopCallback;
import com.hnyc.config.ShopeeConfig;
import com.hnyc.facade.shopee.ShopInfo;
import com.hnyc.shop.domain.ShopShopee;
import com.hnyc.shop.service.IShopShopeeService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @auther zero
 * @date 2023/3/17
 **/
@Component
@Slf4j
public class RegisterShopCallback  implements IRegisterShopCallback {

    @Resource
    IShopShopeeService shopShopeeService;
    @Resource
    ISysUserService sysUserService;
    @Resource
    ShopeeConfig shopeeConfig;
    @Override
    public void registerCallback(ShopInfo shopInfo) {
        // todo shop授权成功，进行回调,判断shop信息是否重复

        ShopShopee exists = shopShopeeService.selectShopShopeeById(shopInfo.getId());
        if(exists!=null){
            exists.setGrantStatus(shopInfo.getStatus());
            exists.setShopName(shopInfo.getShopName());
            exists.setShopRegion(shopInfo.getRegion());
            exists.setUpdatedAt(new Date());
            exists.setShopStatus(shopInfo.getStatus());
            exists.setAuthAt(shopInfo.getAuthTime());
            exists.setExpireAt(shopInfo.getExpireTime());
//            SysUser sysUser = sysUserService.selectUserById(Long.parseLong(shopInfo.getFacadeUser()));
//            shopShopee.setUserId(sysUser.getUserId());
//            shopShopee.setTenancyId(sysUser.getTenancyId());
//            shopShopeeService.insertShopShopee(shopShopee);
            shopShopeeService.updateShopShopee(exists);
        }else{

            ShopShopee shopShopee = new ShopShopee();
            shopShopee.setCreatedAt(new Date());
            // shopId
            shopShopee.setOnlineId(shopInfo.getId());
            shopShopee.setGrantStatus(shopInfo.getStatus());
            shopShopee.setShopName(shopInfo.getShopName());
            shopShopee.setShopRegion(shopInfo.getRegion());
            shopShopee.setUpdatedAt(new Date());
            shopShopee.setShopStatus(shopInfo.getStatus());
            shopShopee.setAuthAt(shopInfo.getAuthTime());
            shopShopee.setExpireAt(shopInfo.getExpireTime());
            shopShopee.setApiVersion(shopeeConfig.apiVersion());
            SysUser sysUser = sysUserService.selectUserById(Long.parseLong(shopInfo.getFacadeUser()));
            shopShopee.setUserId(sysUser.getUserId());
            shopShopee.setTenancyId(sysUser.getTenancyId());
            shopShopeeService.insertShopShopee(shopShopee);
        }


        log.info("商店注册成功，回调通知");
    }
}
